<?php
require_once 'IService.php';
Yii::import("application.models.services");
date_default_timezone_set("Asia/Shanghai");
class Renren implements IService{
	const NAME="renren";
	public $target=FALSE;
	private $api_key = "db1ffe772f504e9790907be9c9a651c7";
	private $secret = "a13bb175bc1940f6b78807e58329264f";
	private $auth_token = "";
	private $session_key = "";
	private $url='http://api.renren.com/restserver.do';
	private $phoneUrl = 'http://m3.api.renren.com/restserver.do';
	public $uid;
	public $ticket;
	private $loginUrl='http://login.api.renren.com/CL.do';
	private $username;
	private $password;
	private $data=Array 
					(		
						"method"=>'',
		 				"format" => "json",
		 				"v" => "1.2",
		 				"api_key" => "db1ffe772f504e9790907be9c9a651c7",
		 				"session_key" =>"",
						
					);
	public function __construct($param1 = NULL, $param2 = NULL) {
		if ($param1 != null && $param2 != null) {
			$this->username = $param1;
			$this->password = $param2;
		}
	}
	
	
	/**
	 * 通用的人人api
	 * 
	 * @param array $data 所有需要post的request
	 * @param String $url  目的地址
	 * @return 返回array
	 */
	private  function api($data = array(),$url='http://login.api.renren.com/CL.do') {
		ksort ( $data );
		$_data = http_build_query ( $data );
		$_data = preg_replace ( "/&/is", '', $_data );
		$_data .= $this->secret;
		$sig = md5 ( $_data );
		
		$data ['sig'] = $sig;
		$o = "";
		foreach ( $data as $k => $v ) {
			$o .= "$k=" . urlencode ( $v ) . "&";
		}
		$data = substr ( $o, 0, - 1 );
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
		$result = curl_exec ( $ch );
		curl_close($ch);
		return $result;
	
	}


	/**
	 * 
	 * 用户登录
	 * @param String $user 用户名
	 * @param String $password 密码
	 */
	public   function login($user=NULL,$password=NULL) {
//		$data = Array ("check" => "0", "user" => $user, "clientName" => "renren", "model" => "gen", "version" => "20100317", "login_info" => '{"ver":"2.2.0.20100317","cellid":"0","from":9100201}', "format" => "json", "password" =>md5($password), "v" => "1.0", "api_key" => "db1ffe772f504e9790907be9c9a651c7", "session_key" => "" );
		if ($user==null&&$password==null){
			$user=$this->username;
			$password=$this->password;
		}
		$data["user"]=$user;
		$data ['check'] = '0';
		$data ['version'] = '20100317';
		$data ['clientName'] = 'renren';
		$data ['login_info'] = '{"ver":"2.2.0.20100317","cellid":"0","from":9100201}';
		$data ['v'] = '1.0';
		$data ['session_key'] = '';
		$data ['api_key'] = db1ffe772f504e9790907be9c9a651c7;
		$data ['format'] = 'json';
		$data ['password'] = $password ;
		$result = json_decode ( $this->api ( $data, $this->loginUrl ), true );
		if(isset($result['error_msg'])||$result==null) throw new Exception("Login Failed:".$result['error_msg']);
		$this->session_key=$result['session_key'];
		$this->ticket=$result['ticket'];
		$this->uid=$result['uid'];
		return $result;
//		setcookie("session_key",$this->session_key);
		
	
	}
	private function feedsCmpByTime($a,$b){
		
	if (strtotime($a['time'])==strtotime($b['time']))
			return 0;
		return strtotime($a['time'])<strtotime($b['time'] ) ? 1 : - 1;
			
	}
	/**
	 * 
	 * 获取用户新鲜事，返回数组。
	 * @param String $type 消息类型（10-状态，20-用户日志，21-分享日志，30-上传照片，31-分享照片，32-分享照片）；
	 * @param String $limit 返回的数据数目
	 * @param String $offset 偏移量
	 */
	private  function getFeedList($limit='30',$offset='0',$type='10'){
		$data = Array 
					(	"offset" => $offset, 	
						"method"=>'phoneclient.getFeedList',
		 				"format" => "json",
		 				"v" => "1.2",
		 				"api_key" => "db1ffe772f504e9790907be9c9a651c7",
		 				"session_key" => $this->session_key,
						"limit"=>$limit, 
						"type"=>$type,
					);
		$result = $this->api ( $data, $this->phoneUrl );
		$result= json_decode ( $result, true );
		$result=$result['newsfeed'];
		
		return $this->resultSort($result);
		
	}
	

	/**
	 * 
	 * 获取用户好友请求信息
	 * @param $count
	 * @param $page
	 */
	private  function getFriendRequestInfo($count='20',$page='1'){
		$data=$this->data;
		$data['v']='1.1';
		$data['method']="phoneclient.getFriendRequestInfo";
		$data['count']=$count;
		$data['page']=$page;
		$data['session_key']=$this->session_key;
//		return $data;
		return json_decode($this->api($data,$this->phoneUrl),true);
		
	}
	
	/**
	 * 
	 * 获取用户个人信息
	 * @param $uid 用户id
	 * @param $fields 获取的内容筛选（可用参数：basic,feed,gossip,visitor,fangle,birthday）
	 */
	private  function _getProfile($uid="",$fields="basic"){
		$data=$this->data;
		$data['v']='1.2';
		if ($uid == "")
			$data ['uid'] = $this->uid;
		$data['method']='phoneclient.getProfile';
		$data['fields']=$fields;
		$data['session_key']=$this->session_key;
		return json_decode($this->api($data,$this->phoneUrl),true);
		
		
	}
	
	/**
	 * 
	 * 发表状态
	 * @param String $status 状态内容
	 * @return mixed
	 */
	private  function setStatus($status){
		$data=$this->data;
		$data['v']='1.1';
		$data['method']='users.setStatus';
		$data['type']='1';
		$data['status']=$status;
		$data['session_key']=$this->session_key;
		return json_decode($this->api($data,$this->phoneUrl),true);
//		return ($data);
	}
	
	/**
	 * 
	 * 回复状态
	 * @param $uid 用户id（回复方）
	 * @param $r_id 被回复的用户id
	 * @param $content 回复内容
	 * @param $status_id 状态id
	 */
	private  function replyStatus($uid,$r_id,$content,$status_id){
		$data=$this->data;
		$data['v']='1.1';
		$data['method']='users.replyStatus';
		$data['uid']=$uid;
		$data['content']=$content;
		$data['session_key']=$this->session_key;
		$data['status_id']=$status_id;
		$data['r_id']=$r_id;
		return json_decode($this->api($data,$this->phoneUrl),true);
	}
	private function resultSort($result=array()){
		foreach ($result as $key =>$value)
			if(strcmp($value['time'], date("m-d ")."99:99")<0)
				$result[$key]['time']=date("Y-").$value['time'];
			else
				$result[$key]['time']=(date("Y-")-1).$value['time'];
		usort($result, array("renren","feedsCmpByTime"));
		return $result;
	}
//	public function getLatest($count = 10, $page = 0){
//		$offset=$count*$page;
//		$result=$this->getFeedList($count,'10',$offset);
//		array_filter($result,"feedFilter");
//		return $result;
//	
//	}
	private function feedFilter($var){
		$ar=array(	"uid"=>$var['from']['0']['id'],
					"user"=>$var['from']['0']['name'],
					"id"=>$var['feed_id'],
					"content"=>$var['content'],
					"source"=>"renren",
					"avatar"=>"http://img.m.renren.com/gn?op=resize&w=50&p=".$var['from']['0']['id'],
					"datetime"=>strtotime($var['time']),
					);
	}


	public static  function register($username=NULL,$password=NULL){
		if ($username!=null&&$password!=NULL){
			$renren=new Renren();
			$result=$renren->login($username, md5($password));
		}
		if (isset($result['error_msg']))
			return $result['error_msg'];
		else{
			$model=new Services;
			$attr=array("param1"=>$username,"param2"=>md5($password),"type"=>self::NAME,"user_id"=>Yii::app()->getModule('user')->user()->id,"is_public"=>TRUE);
			$model->attributes=$attr;
//			$model->user_id=$this->uid;
//			$model->param1=$username;
//			$model->param2=$password;
//			$model->type=self::NAME;
			//$model->save();
			return true;
		}
			
	}
	public function getLatest($count=0,$page=0){
		$this->login();
		$result=$this->getFeedList($count,$page*$count)	;
		$r=array_map(array("renren","feedReform"), $result);
		return $r;
	}
	private  function feedReform($a){
		return array(	"uid"=>$a['from']['0']['id'],
						"id"=>$a['feed_id'],
						"source"=>"RENREN",
						"user"=>$a['from']['0']['name'],
						"avatar"=>"http://img.m.renren.com/gn?op=resize&w=50&h=50&p=".$a['from']['0']['id'],		
						"content"=>$a['content'],
						"datetime"=>strtotime($a['time']),
						);
	}
	public function update($content){
		$this->login();
		$result= $this->setStatus($content);
		
	}
	
	public function reply($target, $id, $content, $reply_to = null) {
		if($target!=self::NAME) return false;
		$this->login();
		$this->replyStatus ( $this->uid, $reply_to, $content, $id );
	}
	
	
	
	public function getProfile($target,$uid){
		if($target!=self::NAME) return false;
		$this->login();
		$result= $this->_getProfile($uid,"basic,feed");
		Yii::trace(print_r($result,true));
		return array(
					"profile"=>array("username"=>$result['user_name'],"avatar"=>$result['head_url']),
					"timeline"=>array_map(array("renren","feedReform"), $result['minifeed']));
	}
	public function getMyName(){
		$this->login();
		$result=$this->getProfile(self::NAME,$this->uid);
		Yii::trace(print_r($result,true));
		return $result['profile']['username'];
	}
	
	public function getMyID() {
		$this->login();
		return $this->uid;
	}
}
?>